package logic

import (
	"context"
	"errors"
	"vip-shop-hub/models/cache"
	"vip-shop-hub/models/mysql"
	"vip-shop-hub/pkg"
	"vip-shop-hub/viprpc/internal/svc"
	"vip-shop-hub/viprpc/viprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *viprpc.UpdatePasswordRequest) (*viprpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User

	if err := user.FIndUserBY(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	if pkg.Md5(in.OldPassword) != user.Password {
		return nil, errors.New("原密码输入错误,请重新输入")
	}

	if in.NewPassword != in.AckNewPassword {
		return nil, errors.New("两次密码输入不一致,请重新输入")
	}

	if in.NewPassword == in.OldPassword {
		return nil, errors.New("新密码和原密码一样,不允许修改,请重新输入")
	}

	resul, _ := cache.Rdb.Get(l.ctx, "sms"+user.Moble).Result()

	if resul != in.SmsCode {
		return nil, errors.New("短信验证码错误,重新输入")
	}

	user.Password = pkg.Md5(in.NewPassword)
	err := user.UpdateUser(mysql.DB)
	if err != nil {
		return nil, errors.New("密码修改失败")
	}
	cache.Rdb.Del(l.ctx, "sms"+user.Moble)
	return &viprpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
